<template>
  <XenPageLayout
    title="编辑访客信息"
    title-align="left"
    navbar-bg-color="#7881de"
    navbar-text-color="#ffffff"
    navbar-icon-color="#ffffff"
    contentStyle="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); padding: 0; height: 100vh; display: flex; flex-direction: column;"
  >
    <!-- 表单内容区域 -->
    <view class="form-container">
      <XenDynamicFormCard
        title="编辑访客信息"
        subtitle="请编辑完整的访客信息以便登记"
        :sections="formSections"
        :modelValue="formData"
        :errors="formErrors"
        footerMode="edit"
        @update:modelValue="handleFormDataChange"
        @fieldBlur="handleFieldBlur"
        @pickerChange="handlePickerChange"
        @datetimeChange="handleDateTimeChange"
        @imageUpload="handleImageUpload"
        @imageSuccess="handleImageSuccess"
        @imageFail="handleImageFail"
        @imageDelete="handleImageDelete"
        @fileUpload="handleFileUpload"
        @fileSuccess="handleFileSuccess"
        @fileFail="handleFileFail"
        @fileDelete="handleFileDelete"
        @save="handleSave"
        @submit="handleSubmit"
      />
    </view>
  </XenPageLayout>
</template>

<script setup lang="ts">
import { onMounted, ref } from "vue";
import XenPageLayout from "@/layouts/XenPageLayout.vue";
import XenDynamicFormCard from "@/components/XenDynamicFormCard.vue";
import { getFormSectionsByPageType } from "./form-config";
import { useVisitorInfo } from "./composables/useInfo";
// 导入统一事件系统
import { VisitorInfoEvents } from "@/utils/eventBus";

// 获取路由参数
const visitorId = ref<string>("");

// 获取编辑页面的表单分组
const formSections = getFormSectionsByPageType("edit");
console.log("编辑页面的表单分组:", formSections);

// 使用访客信息 Composable
const {
  formData,
  formErrors,
  validateField,
  handlePickerChange,
  handleDateTimeChange,
  handleIdCardPhotoUpload,
  handleIdCardPhotoDelete,
  initializeOptions,
  loadVisitorDetail,
  saveVisitor,
  submitVisitor,
  search,
} = useVisitorInfo();

// 表单数据变化处理
const handleFormDataChange = (newData: Record<string, any>) => {
  Object.assign(formData, newData);
};

// 字段失焦处理
const handleFieldBlur = (fieldKey: string) => {
  validateField(fieldKey);
};

// 图片上传处理
const handleImageUpload = async (field: any, event: any) => {
  // 检查是否为身份证上传
  if (field.fileConfig?.isIdCard) {
    if (field.fileConfig.idCardType === "front") {
      await handleIdCardPhotoUpload("idCardFrontPhoto", event);
    } else if (field.fileConfig.idCardType === "back") {
      await handleIdCardPhotoUpload("idCardBackPhoto", event);
    }
  } else {
    // 其他图片上传逻辑
    console.log("普通图片上传:", field.key, event);
  }
};

const handleImageSuccess = (_field: any, _event: any) => {
  // 图片上传成功处理
};

const handleImageFail = (_field: any, _event: any) => {
  // 图片上传失败处理
};

const handleImageDelete = (field: any, event: any) => {
  // 检查是否为身份证删除
  if (field.fileConfig?.isIdCard) {
    if (field.fileConfig.idCardType === "front") {
      handleIdCardPhotoDelete("idCardFrontPhoto");
    } else if (field.fileConfig.idCardType === "back") {
      handleIdCardPhotoDelete("idCardBackPhoto");
    }
  } else {
    // 其他图片删除逻辑
    console.log("普通图片删除:", field.key, event);
  }
};

// 文件上传处理
const handleFileUpload = async (_field: any, _event: any) => {
  // 文件上传逻辑
};

const handleFileSuccess = (_field: any, _event: any) => {
  // 文件上传成功处理
};

const handleFileFail = (_field: any, _event: any) => {
  // 文件上传失败处理
};

const handleFileDelete = (_field: any, _event: any) => {
  // 文件删除处理
};

// 统一的保存/提交处理函数
const processFormData = async (type: "save" | "submit") => {
  try {
    const loadingTitle = type === "submit" ? "提交中..." : "保存中...";
    uni.showLoading({ title: loadingTitle });

    // 使用Composable中的统一处理方法
    const response =
      type === "submit" ? await submitVisitor() : await saveVisitor();

    uni.hideLoading();

    if (response.success && response.data && response.data.ID) {
      // 重新调用search接口获取最新的完整列表数据
      try {
        const searchResponse = await search({});
        if (searchResponse && searchResponse.length > 0) {
          // 发送完整列表数据更新事件
          VisitorInfoEvents.emit("refresh", {
            id: response.data.ID,
            data: searchResponse,
            customAction: type === "submit" ? "submit" : "edit",
          });
        }
      } catch (error) {
        // 如果获取失败，仍然发送简单的刷新事件作为备用方案
        VisitorInfoEvents.emit("refresh", {
          id: response.data.ID,
          customAction: type === "submit" ? "submit" : "edit",
        });
      }

      const successMessage = type === "submit" ? "提交成功" : "保存成功";
      uni.showToast({
        title: successMessage,
        icon: "success",
        success: () => {
          // 成功后返回列表页面
          setTimeout(() => {
            uni.navigateBack();
          }, 1000);
        },
      });
    } else {
      // 校验失败或操作失败，显示具体错误信息
      const errorMessage =
        response.validation?.firstErrorMessage ||
        (response as any).error ||
        `${type === "submit" ? "提交" : "保存"}失败，请重试`;
      uni.showToast({
        title: errorMessage,
        icon: "none",
      });
    }
  } catch (error) {
    uni.hideLoading();
    const errorMessage = `${type === "submit" ? "提交" : "保存"}失败，请重试`;
    uni.showToast({
      title: errorMessage,
      icon: "error",
    });
  }
};

// 保存表单 - 使用统一的处理函数
const handleSave = async () => {
  await processFormData("save");
};

// 显示确认提示框
const showConfirmDialog = async (): Promise<boolean> => {
  return new Promise<boolean>((resolve) => {
    uni.showModal({
      title: "确认提交",
      content: "提交表单后无法修改，是否确认提交？",
      confirmText: "确认提交",
      cancelText: "取消",
      success: (res) => {
        resolve(res.confirm);
      },
      fail: () => {
        resolve(false);
      },
    });
  });
};

// 提交表单 - 使用统一的处理函数
const handleSubmit = async () => {
  // 显示确认提示框
  const confirmResult = await showConfirmDialog();
  if (!confirmResult) return;

  await processFormData("submit");
};

// 组件挂载时加载数据
onMounted(async () => {
  // 先加载选项数据
  await initializeOptions();

  // 获取路由参数中的访客ID
  const pages = getCurrentPages();
  const currentPage = pages[pages.length - 1];
  const options = (currentPage as any).options;

  if (options && options.id) {
    visitorId.value = options.id;
    await loadVisitorDetail(options.id);
  }
});
</script>

<style lang="scss" scoped>
.form-container {
  flex: 1;
  padding: 16px;
  overflow-y: auto;
}
</style>
